<template>
  <div class="library">
    <div class="tableContent">
      <listTableNew v-bind="tableSetting" ref="klTable"></listTableNew>
    </div>
    <dialogPublic
      :title="dialogTitle"
      :show.sync="showDialog"
      @doSubmit="dialogSubmit"
      @doClose="() => (showDialog = false)"
      width="1000px"
    >
      <div v-if="showDialog" class="popup_wrapper">
        <div class="attachment_wrapper">
          <editForm
            :formConfig="documentConfig"
            ref="documentForm"
            :formData="documentFormData"
          >
          </editForm>
          <div class="attachment_row">
            <div class="left">附件</div>
            <attachFormNew
              ref="docRef"
              :attachSetting="attachSetting"
              @uploadSuccess="uploadSuccess"
              showTime
              isDelete
              multiple
            ></attachFormNew>
          </div>
        </div>
      </div>
    </dialogPublic>
  </div>
</template>

<script>
import {
  queryDocumentList,
  uploadDocumentApi,
  deleteDocumentApi
} from "@/api/equipmentLedger/equipmentDocument.js";
import {
  getParentIdsApi, //获取某个节点的所有父节点
} from "@/api/equipmentLedger/equipmentManage";
export default {
  props: ["equipId", "fileFullPath", 'equipName'],
  components: {
  },
  data() {
    return {
      fileType: [],
      fullPath: "",
      dialogTitle: "上传图档附件",
      showDialog: false,
      btnArr: [],
      nodeKey: "id",
      itemArrs: [],
      defaultNodeId: "",
      documentConfig: {
        labelWidth: "160px",
        itemArr: [
          {
            label: "附件类型",
            prop: "type",
            type: "select",
            selectOption: [
              {
                value: "overhaul",
                label: "大修资料",
              },
              {
                value: "renovation",
                label: "更新改造",
              },
              {
                value: "technical",
                label: "技术改造",
              },
              {
                value: "failure",
                label: "故障案例",
              },
              {
                value: "other",
                label: "其他技术资料",
              },
            ],
            required: true,
            span: 12,
          },
        ],
      },
      documentFormData: {},
      attachSetting: {
        businessId: "", //单据的ID
        businessType: "base",
      },
      tableSetting: {
        showCustomBtn: true,
        showFilterBtn: true,
        pageConfig: {
          pageCode: "equipmentManage", //页面标识，用来存储过滤器以及自定义列的时候用
          userId: this.$store.getters.userInfo.id,
        },
        searchObj: {
          queryData: {
            page: 1,
            pageSize: 15,
            search: 'false',
            type: "",
          },
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          searchArr: [
            {
              label: "向上归集",
              model: "search",
              unclearable: true,
              type: "select",
              option: [
                { label: "是", value: 'false' },
                { label: "否", value: 'true' },
              ],
            },
            {
              type: "input",
              label: "文件名称",
              model: "fileName",
            },
            {
              type: "select",
              label: "文件类型",
              model: "type",
              option: [
                {
                  value: "overhaul",
                  label: "大修资料",
                },
                {
                  value: "renovation",
                  label: "更新改造",
                },
                {
                  value: "technical",
                  label: "技术改造",
                },
                {
                  value: "failure",
                  label: "故障案例",
                },
                {
                  value: "other",
                  label: "其他技术资料",
                },
              ],
            },
            {
              type: "userOnly",
              label: "创建人",
              model: "createByName",
            },
            {
              label: "创建时间",
              model: "createTime",
              type: "datetimerange",
            },
          ],
        },
        //过滤器的值
        filterFormData: {},
        //过滤器的默认值
        defaultFilterData: {},
        userCustomData: [],
        actionList: [
          {
            name: "新建",
            icon: "el-icon-plus",
            disabled: !this.$store.getters.isBtnAuth("add"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.showDialog = true;
            },
          },
        ],
        column: [
          {
            label: "文件名称",
            prop: "fileName",
            sortable: "custom",
            // width: "300px",
            showTooltip: true,
          },
          {
            label: "文件类型",
            prop: "type",
            sortable: "custom",
            width: 180,
            formatter: (row) => {
              const option = [
                {
                  value: "overhaul",
                  label: "大修资料",
                },
                {
                  value: "renovation",
                  label: "更新改造",
                },
                {
                  value: "technical",
                  label: "技术改造",
                },
                {
                  value: "failure",
                  label: "故障案例",
                },
                {
                  value: "other",
                  label: "其他技术资料",
                },
              ];
              return option.find(item => item.value === row.type).label
            },
          },
          {
            label: "所属设备",
            prop: "equipmentName",
            sortable: "custom",
            formatter: (row) => {
              return row.equipmentName || '未关联所属设备'
            }
          },
          {
            label: "创建人",
            prop: "createByName",
            sortable: "custom",
            width: 100,
          },
          {
            label: "创建时间",
            prop: "createTime",
            sortable: "custom",
            width: 158,
          },
          {
            label: "操作",
            textAlign: "center",
            type: "button",
            buttonArr: [
              {
                text: "下载",
                isShow: () => {
                  return true;
                },
                methods: (row, index) => {
                  this.downloadDocument(row)
                },
              },
              {
                text: "删除",
                isShow: (row) => {
                  return this.hasHandleReportPermission || row.createBy === this.$store.getters.currentInfo.currLeader;
                },
                methods: (row, index) => {
                  this.$confirm("确定要删除该条数据吗", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  })
                    .then(() => {
                      this.deleteDocument(row)
                    })
                    .catch((e) => {});
                },
              },
            ],
          },
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (row) => {},
        },
      },
      //文件分类
      typeObj: {
        imge: ["jpg", "jpeg", "gif", "bmp", "png", "svg"],
        pdf: ["pdf"],
        video: ["mp4", "m2v", "mkv", "rmvb", "wmv", "avi", "flv", "mov", "m4v"],
        html: ["htm", "html"],
        docx: ["doc", "docx", "docm", "dotx", "dotm"],
        xlsx: ["xls", "xlsx", "xlsm", "xltx", "xltm", "xlsb", "xlam"],
        txt:["txt"],
        pptx: ["ppt", "pptx", "pot", "potx", "pptm", "ppsx", "ppsm"],
        zip: ["zip", "rar", "7z", "7-zip", "tar", "gzip", "bz2", "jar"],
      },
    };
  },
  computed: {
    disabled() {
      return !this.$store.getters["isBtnAuth"]("uploadFiles");
    },
    // 当前用户是否是管理员，用于判断是否有此单数据操作权限
    hasHandleReportPermission() {
      let roleList = this.$store.getters.mineUserInfo.userOwnJurisdictionBean.roleBean;
      // 超级管理员
      let GMflag = roleList.some(item => item.roleType === 'role_root')
      return GMflag
    },
  },
  async created() {
    const { data } = await getParentIdsApi(this.equipId || "");
    this.fullPath = data.join("/") + "/" + this.equipId;
    this.init();
    /* 添加监听事件 */
    window.addEventListener("storage", this.updateData);
  },
  beforeDestroy() {
    /* 删除监听事件 */
    window.removeEventListener("storage", this.updateData);
  },
  watch: {
    equipId: {
      async handler(val) {
        const { data } = await getParentIdsApi(val || "");
        this.fullPath = data.join("/") + "/" + val;
        this.init();
      },
    },
  },
  methods: {
    init() {
      this.$nextTick(() => {
        this.$refs.klTable.getTableConfig(); //需要显示过滤器以及自定义列时要提前调用,不需要过滤器时不调用
        setTimeout(() => {
          this.$refs.klTable.searchData();
        }, 1000);
      });

      let dirtData = this.$store.getters.dirtData("documents_type");
      this.attachSetting.businessId = this.equipId
      this.fileType = dirtData.map((item) => {
        let obj = {
          name: item.label,
          attachSetting: {
            businessId: this.equipId,
            businessType: item.value,
          },
        };
        return obj;
      });
    },
    getTableData(params, sortStr) {
      let form = { ...params };
      if (sortStr) {
        form.orders = sortStr;
      }
      form.fullPath = this.fullPath || "";
      queryDocumentList(form)
        .then((res) => {
          let data = res.data.list || [];
          let total = res.data.total || 0;
          this.$set(this.tableSetting, "tableData", data);
          this.$set(this.tableSetting, "totalNumber", total);
        })
        .catch((err) => {
          this.$set(this.tableSetting, "tableData", []);
          this.$set(this.tableSetting, "totalNumber", 0);
        });
    },
    updateData() {
      this.$refs.klTable.searchData(false, false);
    },
    // 确认上传图档附件
    async dialogSubmit() {
      const { type } = await this.$refs.documentForm.getFormData();
      this.attachSetting.businessType = type;
      this.uploadDocument();
    },
    // 上传图档附件(附件组件)
    uploadDocument() {
      this.$refs.docRef.doSubmitFiles();
    },
    // 上传附件成功回调函数（并调用图档附件接口）
    uploadSuccess(data) {
      const filterList = data.map((item) => {
        return {
          equipmentId: this.equipId,
          equipmentName: this.equipName,
          fileId: item.path,
          fileName: item.name,
          fullPath: this.fileFullPath,
          fullPathName: this.fileFullPathName,
          type: this.attachSetting.businessType,
        };
      });
      uploadDocumentApi(filterList)
        .then(() => {
          this.showDialog = false;
          this.updateData();
        })
        .catch(() => {
          this.$message.error("图档附件上传失败!");
        })
        .finally(() => {
          this.attachSetting.businessType = "base"
        })
    },
    // 删除图档
    async deleteDocument(row) {
      // TODO 这里有个待解决的问题：此处删除只删除图档表里对文件的引用，文件服务器的实际文件还是存在的。
      try {
        const { code } = await deleteDocumentApi(row.id)
        if(code !== 200) throw new Error('deleteDocumentApi请求异常')
        this.$message.success('图档文件删除成功!')
        this.updateData();
      } catch (error) {
        console.error(error)
        this.$message.error('图档文件删除失败!')
      }
    },
    // 预览图档
    async previewDocument(row) {
      const { fileName: name, fileId: path} = row
      const extension = row.fileId.split('.')[1]
      let type = "";
      for (const key in this.typeObj) {
        //循环遍历typeObj
        let arr = this.typeObj[key];
        if (arr.includes(extension)) {
          //比较找到typeObj相应的后缀名，从而判断它属于哪个类型
          type = key;
        }
      }
    },
    // 下载图档
    downloadDocument(row) {
      const fetchUrl = process.env.NODE_ENV === 'production' ? 'https://eamv2.guangdongwater.com:8001' : 'http://10.11.228.110:30001'
      this.$message('文件开始下载，请耐心等待...')
      fetch(`${fetchUrl}/eam-common-web/attachment/download/${row.fileId}`, {
        method: 'get',
        responseType: 'blob',
        headers: {
          Jwt_token: localStorage.getItem('GDH_WATER_TOKEN'),
          Dynamic_data_source: localStorage.getItem("currDs")
        }
      }).then((resp) => {
          const filenameEncode = resp.headers.get('Content-Disposition').split('filename=')[1]
          const filename = decodeURIComponent(filenameEncode)
          return new Promise(async (resolve, reject) => {
            const blob = await resp.blob()
            resolve({
              blob,
              filename: filename
            })
        })
      }).then((res) => {
        const url = URL.createObjectURL(res.blob)
        const aLink = document.createElement('a')
        aLink.href = url
        aLink.setAttribute('download', res.filename)
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink)
        this.$message.success('下载成功!')
      }).catch((err) => {
        this.$message.error('下载失败，文件大小过大或网络异常!')
      })
    },
    // base64编码
    base64Encode(str) {
      return btoa(unescape(encodeURIComponent(str)));
    },
  },
};
</script>

<style lang="less" scoped>
.library {
  height: 100%;
  overflow: auto;
  .tableContent {
    padding: 20px;
    height: calc(100% - 40px);
  }

  .popup_wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
    overflow: hidden;
    .tree_wrapper {
      width: 300px;
      height: 100%;
      overflow: hidden;
    }

    .attachment_wrapper {
      padding: 20px 0;
      width: calc(100% - 300px);

      .attachment_row {
        display: flex;
        flex-direction: row;
        align-items: center;
        .left {
          padding-right: 12px;
          width: 160px;
          text-align: right;
        }
      }
    }
  }
}
</style>
